package com.qf.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @date 2025/8/20
 * @desc
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserDetailServiceImpl userDetailService;

    /**
     * 用于处理认证异常的类
     */
    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;

    /**
     * 注入处理权限异常的类
     */
    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    /**
     * 注入JWT拦截器
     */
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    /**
     * 新增代码，用于获取AuthenticationManager对象，在登录的业务层进行调用
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    /**
     * 配置认证信息,密码加密
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder());
    }

    /**
     * 配置权限信息
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/user/login","/user/selectByUsername").permitAll()
                .antMatchers("/**").authenticated( );

        /**
         *  cors() 启用跨域资源共享（CORS）支持
         *  and() 连接
         *  csrf().disable() 禁用CSRF（跨站请求伪造）保护
         */

        http.cors().and().csrf().disable();
      // 设置认证失败时的处理类
        http.exceptionHandling().authenticationEntryPoint(unauthorizedHandler);
        // 设置权限异常时的处理类
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
        // 【重点】基于token，所以不需要session，即所以认证信息都存放在token中，不需要session
        http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        // 设置JWT拦截器
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }
}